package com.winhxd.b2c.order.service.impl;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.cache.Lock;
import com.winhxd.b2c.common.cache.RedisLock;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.constant.OrderSMSConstant;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.model.CustomerDeliveryInfo;
import com.winhxd.b2c.common.domain.customer.model.CustomerShoppingMallRule;
import com.winhxd.b2c.common.domain.customer.vo.CustomerUserInfoVO;
import com.winhxd.b2c.common.domain.message.condition.MiniMsgCondition;
import com.winhxd.b2c.common.domain.message.condition.MiniTemplateData;
import com.winhxd.b2c.common.domain.message.condition.SMSCondition;
import com.winhxd.b2c.common.domain.message.enums.MiniMsgTypeEnum;
import com.winhxd.b2c.common.domain.order.condition.*;
import com.winhxd.b2c.common.domain.order.enums.*;
import com.winhxd.b2c.common.domain.order.model.*;
import com.winhxd.b2c.common.domain.order.vo.*;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.feign.customer.DeliveryInfoServiceClient;
import com.winhxd.b2c.common.mq.MQDestination;
import com.winhxd.b2c.common.mq.StringMessageSender;
import com.winhxd.b2c.common.util.DateUtil;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.common.util.MessageSendUtils;
import com.winhxd.b2c.common.util.SecurityCheckUtil;
import com.winhxd.b2c.order.dao.*;
import com.winhxd.b2c.order.service.OrderAfterSaleService;
import com.winhxd.b2c.order.service.OrderManagementService;
import com.winhxd.b2c.order.service.OrderQueryService;
import com.winhxd.b2c.order.util.OrderUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class OrderManagementServiceImpl implements OrderManagementService{

    private static final Logger logger = LoggerFactory.getLogger(OrderManagementServiceImpl.class);

    private static final String KEYWORD1 = "keyword1";
    private static final String KEYWORD2 = "keyword2";
    private static final String KEYWORD3 = "keyword3";
    private static final String KEYWORD4 = "keyword4";


    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderConsigneeMessageMapper orderConsigneeMessageMapper;
    @Autowired
    private OrderAfterSaleService orderAfterSaleService;
    @Autowired
    private OrderMemberMessageMapper orderMemberMessageMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderExpressInfoMapper orderExpressInfoMapper;
    @Autowired
    OrderAfterSaleDetailMapper orderAfterSaleDetailMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDictInfoMapper orderDictInfoMapper;

    @Autowired
    private OrderQueryService orderQueryService;
    @Autowired
    private OrderRefundInfoMapper orderRefundInfoMapper;

    @Autowired
    OrderProductAttributeMapper orderProductAttributeMapper;

    @Autowired
    DeliveryInfoServiceClient deliveryInfoServiceClient;

    @Autowired
    private StringMessageSender stringMessageSender;

    @Autowired
    private Cache cache;

    @Autowired
    private OrderRebateRecordMapper orderRebateRecordMapper;
    @Autowired
    private MessageSendUtils messageServiceClient;
    @Autowired
    CustomerServiceClient customerServiceClient;
    @Autowired
    MessageSendUtils messageSendUtils;



    @Override
    public List<OrderManagementListVO> findOrderManagementList(OrderManagementListCondition condition) {
        DecimalFormat df = new DecimalFormat("##,##0.00");
        condition.setOrderNo(condition.getOrderNo().trim());
        List<OrderManagementListVO> orderManagementListVOList = orderInfoMapper.selectOrderManagementList(condition);
        for (OrderManagementListVO vo:orderManagementListVOList) {
            if(null != vo.getTotalMoney()){
                vo.setTotalMoneyStr("￥"+df.format(vo.getTotalMoney()));
            }
        }
        return orderManagementListVOList;
    }

    @Override
    public OrderShoppingListVO findShoppingList(OrderShoppingListCondition condition) {
        String log = "查询购物清单---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderShoppingListVO orderShoppingListVO = new OrderShoppingListVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        List<OrderDetailVO> orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);
        orderShoppingListVO.setOrderInfo(orderInfoVO);
        orderShoppingListVO.setOrderDetail(orderDetailVOList);
        return orderShoppingListVO;
    }

    @Override
    public OrderDistributionListVO findDistributionList(OrderDistributionListCondition condition) {
        String log = "查询配货清单---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderDistributionListVO orderDistributionListVO = new OrderDistributionListVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        List<OrderDetailVO> orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);
        OrderConsigneeMessage orderConsigneeMessage = orderConsigneeMessageMapper.selectOrderConsigneeMessageByOrderNo(condition.getOrderNo());
        orderDistributionListVO.setOrderInfo(orderInfoVO);
        orderDistributionListVO.setOrderDetail(orderDetailVOList);
        orderDistributionListVO.setOrderConsigneeMessages(orderConsigneeMessage);
        return orderDistributionListVO;
    }

    @Override
    public OrderManagementDetailsVO findOrderDetails(OrderDetailsCondition condition) {
        String log = "查询订单详情---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderManagementDetailsVO orderManagementDetailsVO = new OrderManagementDetailsVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        List<OrderDetailVO> orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);
        OrderConsigneeMessage orderConsigneeMessage = orderConsigneeMessageMapper.selectOrderConsigneeMessageByOrderNo(condition.getOrderNo());
        OrderMemberMessage orderMemberMessage = orderMemberMessageMapper.selectOrderMemberMessageByOrderNo(condition.getOrderNo());
        orderManagementDetailsVO.setOrderInfo(orderInfoVO);
        orderManagementDetailsVO.setOrderDetail(orderDetailVOList);
        orderManagementDetailsVO.setOrderConsigneeMessages(orderConsigneeMessage);
        orderManagementDetailsVO.setOrderMemberMessage(orderMemberMessage);
        return orderManagementDetailsVO;
    }

    @Transactional
    @Override
    public void modifyOrderStatusToClose(OrderStatusToCloseCondition condition) {
        String log = "后台管理-订单详情-关闭订单---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        //根据订单号查询订单，该订单是否是待支付
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        if(null != orderInfoVO){
            if(OrderStatusEnum.WAIT_PAY.getStatusCode() == orderInfoVO.getStatus()){
                Date nowDate = new Date();
                //修改订单主表
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setOrderNo(orderInfoVO.getOrderNo());
                orderInfo.setStatus(OrderStatusEnum.CLOSE.getStatusCode());
                orderInfo.setCloseTime(nowDate);
                orderInfo.setUpdated(nowDate);
                orderInfo.setUpdatedBy(condition.getUserName());
                int n = orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
                if(n==0){
                    throw new BusinessException(BusinessCode.CODE_405401,"关闭订单失败");
                }
                //增加订单日志
                OrderLog orderLog = new OrderLog();
                orderLog.setOrderNo(orderInfoVO.getOrderNo());
                orderLog.setOperationProperty(OrderOperationPropertyEnum.CLOSE_ORDER.getPropertyDes());
                orderLog.setCreated(nowDate);
                int n2 = orderLogMapper.insertSelective(orderLog);
                if(n2==0){
                    throw new BusinessException(BusinessCode.CODE_405401,"关闭订单失败");
                }
                //收益改为已关闭
                OrderRebateRecord orderRebateRecord = new OrderRebateRecord();
                orderRebateRecord.setStatus(OrderRebateStatusEnum.HAS_CLOSED.getStatusCode());
                orderRebateRecord.setOrderNo(orderInfoVO.getOrderNo());
                orderRebateRecordMapper.updateStatusByOrderNo(orderRebateRecord);
            }else {
                throw new BusinessException(BusinessCode.WRONG_ORDER_STATUS,"订单状态错误");
            }
        }else {
            throw new BusinessException(BusinessCode.ORDER_DOES_NOT_EXIST,"订单不存在");
        }
    }

    @Override
    public OrderCollectAndRefundRecordVO findCollectAndRefundRecord(OrderCollectAndRefundRecordCondition condition) {
        String log = "后台管理-订单详情-收退款记录---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderCollectAndRefundRecordVO orderCollectAndRefundRecordVO = new OrderCollectAndRefundRecordVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        //退款信息
        List<OrderRefundInfoVO> orderRefundInfoVOList = orderRefundInfoMapper.selectOrderRefundInfoByCondition(orderAfterSaleCondition);
        //查询退款中的sku，然后查询详情,把detail中的商品名称、属性和数量放到退款VO中
        List<OrderDetailVO> orderDetailVOList;
        if (!CollectionUtils.isEmpty(orderRefundInfoVOList)) {
            for (OrderRefundInfoVO refundInfoVO : orderRefundInfoVOList) {
                //set整单退
                if(refundInfoVO.getType().intValue() == AfterSaleRefundTypeEnum.WAIT_DELIVERING_REFUND.getTypeCode().intValue()){
                    orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);
                    Integer number = 0;
                    for (OrderDetailVO orderDetail: orderDetailVOList) {
                        number += orderDetail.getNumber();
                    }
                    refundInfoVO.setSpuName("整单退");
                    refundInfoVO.setNumber(number);
                }else{
                    orderAfterSaleCondition.setSkuId(refundInfoVO.getSkuId());
                    orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);
                    for (OrderDetailVO orderDetail: orderDetailVOList) {
                        refundInfoVO.setSpuName(orderDetail.getSpuName());
                        refundInfoVO.setNumber(orderDetail.getNumber());
                        refundInfoVO.setAttributes(orderDetail.getAttributes());
                    }
                }
            }
        }
        orderCollectAndRefundRecordVO.setOrderInfo(orderInfoVO);
        orderCollectAndRefundRecordVO.setOrderRefundInfo(orderRefundInfoVOList);
        return orderCollectAndRefundRecordVO;
    }

    @Override
    public OrderReceivingAndDeliveryRecordVO findReceivingAndDeliveryRecord(OrderReceivingAndDeliveryRecordCondition condition) {
        String log = "后台管理-订单详情-收发货记录---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderReceivingAndDeliveryRecordVO orderReceivingAndDeliveryRecordVO = new OrderReceivingAndDeliveryRecordVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        OrderConsigneeMessage orderConsigneeMessage = orderConsigneeMessageMapper.selectOrderConsigneeMessageByOrderNo(condition.getOrderNo());
        List<OrderExpressInfoVO> orderExpressInfoVOList = orderExpressInfoMapper.selectOrderExpressInfoByCondition(orderAfterSaleCondition);
        orderReceivingAndDeliveryRecordVO.setOrderInfo(orderInfoVO);
        orderReceivingAndDeliveryRecordVO.setOrderConsigneeMessages(orderConsigneeMessage);
        orderReceivingAndDeliveryRecordVO.setOrderExpressInfo(orderExpressInfoVOList);
        return orderReceivingAndDeliveryRecordVO;
    }

    @Override
    public OrderLogVO findOrderLog(OrderLogCondition condition) {
        String log = "后台管理-订单详情-日志记录---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        OrderLogVO orderLogVO = new OrderLogVO();
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(condition.getOrderNo());
        OrderInfoVO orderInfoVO = orderInfoMapper.selectOrderInfoByCondition(orderAfterSaleCondition);
        List<OrderLog> orderLogList = orderLogMapper.selectOrderLogByOrderNo(condition.getOrderNo());
        orderLogVO.setOrderInfo(orderInfoVO);
        orderLogVO.setOrderLog(orderLogList);
        return orderLogVO;
    }

    @Override
    public List<OrderRebateInformationVO> findRebateInformation(OrderRebateInformationCondition condition) {
        String log = "后台管理-订单详情-返利记录---";
        //参数非空验证
        if (condition==null|| StringUtils.isBlank(condition.getOrderNo())){
            logger.info(log+"订单号为空");
            throw new BusinessException(BusinessCode.ORDER_NO_EMPTY);
        }
        List<OrderRebateInformationVO> orderRebateInformationVOS = orderRebateRecordMapper.selectRebateInformation(condition);
        //只显示有返利的等级
        Iterator<OrderRebateInformationVO> informationVOIterator = orderRebateInformationVOS.iterator();
        while (informationVOIterator.hasNext()){
            OrderRebateInformationVO orderRebateInformationVO = informationVOIterator.next();
            //根据customerId获取姓名
            if (null != orderRebateInformationVO.getAgentId()){
                ResponseResult<CustomerUserInfoVO> ret = customerServiceClient.getCustomerUserInfoById(orderRebateInformationVO.getAgentId());
                if( null!=ret && null != ret.getData() && null != ret.getData().getNickName()){
                    orderRebateInformationVO.setAgentName(ret.getData().getNickName());
                }
            }
            //去除空值和为零的返利信息
            if( null == orderRebateInformationVO.getProfit() && null == orderRebateInformationVO.getIntegral()){
                informationVOIterator.remove();
                continue;
            }
            if(orderRebateInformationVO.getProfit().compareTo(BigDecimal.valueOf(0))==0 && orderRebateInformationVO.getIntegral()<1){
                informationVOIterator.remove();
            }
        }
        return orderRebateInformationVOS;
    }


    @Override
    public OrderDeliverGoodsInfoVO getDeliverGoodsInfo(OrderDeliverGoodsInfoCondition condition) {
        String log="获取待发货信息---";
        logger.info(log+"参数："+condition);
        String orderNo=condition.getOrderNo();
        log=log+"订单号："+orderNo;
        if (condition==null|| StringUtils.isBlank(orderNo)){
            logger.info(log+"参数有误");
            throw new BusinessException(BusinessCode.CODE_406101);
        }
        OrderDeliverGoodsInfoVO orderDeliverGoodsInfo= new OrderDeliverGoodsInfoVO();

        OrderInfo orderInfo =orderInfoMapper.selectByOrderNo(orderNo);
        OrderInfoVO orderInfoVO=new OrderInfoVO();
        if (orderInfo != null){
            BeanUtils.copyProperties(orderInfo,orderInfoVO);
        }
        //获取订单商品信息
        OrderAfterSaleCondition orderAfterSaleCondition = new OrderAfterSaleCondition();
        orderAfterSaleCondition.setOrderNo(orderNo);
        List<OrderDetailVO> orderDetailVOList = orderAfterSaleService.getOrderDetailByCondition(orderAfterSaleCondition);

        orderInfoVO.setOrderDetailVOList(orderDetailVOList);
        orderDeliverGoodsInfo.setOrderInfo(orderInfoVO);
        // 获取收货信息
        OrderConsigneeMessage orderConsigneeMessage = orderConsigneeMessageMapper.selectByOrderNo(orderNo);
        OrderConsigneeMessageVO consigneeMessageVO=new OrderConsigneeMessageVO();
        if(null != orderConsigneeMessage){
            BeanUtils.copyProperties(orderConsigneeMessage,consigneeMessageVO);
        }
        orderDeliverGoodsInfo.setOrderConsigneeMessage(consigneeMessageVO);
        //获取快递方式
        OrderDictInfo dictInfo = new OrderDictInfo();
        dictInfo.setType(5);
        List<OrderDictInfoVO> dictInfoList=orderDictInfoMapper.selectListByModel(dictInfo);
        orderDeliverGoodsInfo.setDictInfoList(dictInfoList);
        //获取物流公司
        ResponseResult<List<CustomerDeliveryInfo>> ret = deliveryInfoServiceClient.findDeliveryInfo();
        if(null == ret.getData()){
            logger.error("订单：{},获取物流公司, 返回结果:code={} 物流公司不存在！~", orderInfo.getOrderNo()
                    , ret == null ? null : ret.getCode());
        }
        orderDeliverGoodsInfo.setDeliveryInfoList(ret.getData());
        return orderDeliverGoodsInfo;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer saveDeliverGoods(OrderDeliverGoodsInfoCondition condition) {
        //缓存获取订单自动收货时间
        CustomerShoppingMallRule customerShoppingMallRule = JsonUtil.parseJSONObject(cache.get(CacheName.SHOPPING_MALL_RULE), CustomerShoppingMallRule.class);
        if (customerShoppingMallRule == null || null == customerShoppingMallRule.getOrderReceiveRule()) {
            logger.error("缓存读取自动收货时间为空");
            throw new BusinessException(BusinessCode.CODE_406204);
        }
        //自动收货时间
        long orderReceiveTime = customerShoppingMallRule.getOrderReceiveRule()*24*60*60*1000;

        int result = 0;
        String log = "保存发货信息---";
        logger.info(log + "参数：" + condition);

        String orderNo = StringUtils.trim(condition.getOrderNo());
        String userName = StringUtils.trim(condition.getUserName());
        String mobile = StringUtils.trim(condition.getMobile());
        String address = StringUtils.trim(condition.getAddress());
        Integer expressType = condition.getExpressType();
        String remark = StringUtils.trim(condition.getRemark());
        String expressCompany = StringUtils.trim(condition.getExpressCompany());
        String expressCompanyNo = StringUtils.trim(condition.getExpressCompanyNo());
        String expressNo = StringUtils.trim(condition.getExpressNo());
        //参数非空验证
        if (condition == null || StringUtils.isBlank(orderNo) || StringUtils.isBlank(userName)
                || StringUtils.isBlank(mobile) || StringUtils.isBlank(address) || expressType == null) {
            logger.info(log + "参数有误");
            throw new BusinessException(BusinessCode.CODE_406101);
        }
        //校验手机号格式
        if (!SecurityCheckUtil.validateMobile(mobile)) {
            logger.info(log + "输入的收货人手机号" + mobile + "格式不正确");
            throw new BusinessException(BusinessCode.CODE_200003);
        }
        //快递邮寄-参数非空验证
        if (expressType == DeliveryTypeEnum.EXPRESS_EMAIL.getTypeCode() && (StringUtils.isBlank(expressCompanyNo)
                || StringUtils.isBlank(expressCompany) || StringUtils.isBlank(expressNo))) {
            logger.info(log + "参数有误");
            throw new BusinessException(BusinessCode.CODE_406101);
        }
        //验证快递类型 是否正确
        if (expressType != DeliveryTypeEnum.SELF_PICK_UP.getTypeCode() &&
                expressType != DeliveryTypeEnum.EXPRESS_EMAIL.getTypeCode()) {
            logger.info(log + "快递类型有误");
            throw new BusinessException(BusinessCode.CODE_405801);
        }


        String lockKey = CacheName.CACHE_KEY_APPLY_AFTER_SALE+orderNo;
        Lock lock = new RedisLock(cache, lockKey, 2000);
        try {
            if(lock.tryLock()) {

                OrderInfo orderInfo = orderInfoMapper.selectByOrderNo(orderNo);
                if (orderInfo == null || orderInfo.getStatus().intValue() != OrderStatusEnum.WAIT_DELIVERING.getStatusCode()) {
                    logger.info(log + "订单状态有误");
                    throw new BusinessException(BusinessCode.CODE_405802);
                }

                OrderAfterSaleDetail afterSaleDetail = orderAfterSaleDetailMapper.selectOrderAfterSaleDetailByOrderNo(orderNo);
                //用户提交申请退款，审核通过
                if (null != afterSaleDetail && afterSaleDetail.getResultStatus().intValue() == AfterSaleAuditStatusEnum.YES.getTypeCode().intValue() &&
                        afterSaleDetail.getCompleteStatus().intValue() == CommonStatusEnum.YES.getTypeCode().intValue()) {
                    logger.info("订单：{}  未发货申请退款，审核通过，无法执行送货操作", orderInfo.getOrderNo());
                    throw new BusinessException(BusinessCode.CODE_405806);
                }

                //用户提交申请退款，处理中
                if (null != afterSaleDetail && afterSaleDetail.getResultStatus().intValue() == AfterSaleAuditStatusEnum.PROCESSING.getTypeCode().intValue()) {
                    logger.info("订单：{}  未发货申请退款，审核中，无法执行送货操作", orderInfo.getOrderNo());
                    throw new BusinessException(BusinessCode.CODE_405806);
                }

                //验证收货地址是否发生变化，如果发生变化，把之前的记录置为无效，并保存最新的记录
                OrderConsigneeMessage consigneeMessage = orderConsigneeMessageMapper.selectByOrderNo(orderNo);
                if (consigneeMessage == null) {
                    logger.info(log + "未获取到地址信息");
                    throw new BusinessException(BusinessCode.CODE_405803);
                }
                Date now = new Date();
                //更新订单状态为：已发货(待收货)
                orderInfo.setStatus(OrderStatusEnum.WAIT_RECEIVING.getStatusCode());
                orderInfo.setUpdated(now);
                orderInfo.setUpdatedBy(condition.getLoginUser());
                orderInfo.setSendTime(now);
                orderInfo.setAutoReceiveDay(Long.valueOf(customerShoppingMallRule.getOrderReceiveRule()));
                int updateOrderStatus = orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
                if (updateOrderStatus < 1) {
                    logger.info(log + "订单状态更新失败");
                    throw new BusinessException(BusinessCode.CODE_405804);
                }
                //保存订单日志
                OrderLog orderLog = new OrderLog();
                orderLog.setCreated(now);
                orderLog.setOrderNo(orderNo);
                orderLog.setOperationProperty(OrderOperationPropertyEnum.DELIVERED.getPropertyDes());
                orderLogMapper.insertSelective(orderLog);
                //验证收货地址是否发生变化，如果发生变化，把之前的记录置为无效，并保存最新的记录
                if (!consigneeMessage.getName().equals(userName)
                        || !consigneeMessage.getMobile().equals(mobile)
                        || !consigneeMessage.getAddress().equals(address)) {
                    //地址发生变化，老地址置为无效
                    consigneeMessage.setStatus(CommonStatusEnum.NO.getTypeCode());
                    orderConsigneeMessageMapper.updateByPrimaryKeySelective(consigneeMessage);
                    //重新保存新地址
                    consigneeMessage.setId(null);
                    consigneeMessage.setCreated(now);
                    consigneeMessage.setStatus(CommonStatusEnum.YES.getTypeCode());
                    consigneeMessage.setName(userName);
                    consigneeMessage.setMobile(mobile);
                    consigneeMessage.setAddress(address);
                    orderConsigneeMessageMapper.insertSelective(consigneeMessage);
                }
                //保存物流信息
                OrderExpressInfo expressInfo = new OrderExpressInfo();
                BeanUtils.copyProperties(condition, expressInfo);
                expressInfo.setCreated(now);
                expressInfo.setCreatedBy(condition.getLoginUser());
                expressInfo.setSendTime(now);
                expressInfo.setRemark(remark);
                expressInfo.setType(OrderExpressTypeEnum.NORMAL.getTypeCode());
                result = orderExpressInfoMapper.insertSelective(expressInfo);

                //发送延时消息自动收货 （判断自动发货时间（天），是否大于自定义的mq延时消息的发送时间间隔 ）
                if (orderReceiveTime > OrderMessageHandler.INTERVAL_SEND_TIME) {
                    stringMessageSender.send(MQDestination.OUTLET_ORDER_AUTO_RECEIVING, orderInfo.getOrderNo(), OrderMessageHandler.INTERVAL_SEND_TIME);
                } else {
                    stringMessageSender.send(MQDestination.OUTLET_ORDER_AUTO_RECEIVING, orderInfo.getOrderNo(), (int) orderReceiveTime);
                }


                try {
                    //获取用户信息
                    ResponseResult<CustomerUserInfoVO> ret = customerServiceClient.getCustomerUserInfoById(orderInfo.getCustomerId());

                    //发货短信通知TO收货人
                    if (null != customerShoppingMallRule.getDeliverMobileStatus() && customerShoppingMallRule.getDeliverMobileStatus().equals(1)) {
                        String content = MessageFormat.format(OrderSMSConstant.deliverGoods_template, expressCompany, expressNo, orderInfo.getOrderNo());
                        SMSCondition sMSCondition = new SMSCondition();
                        sMSCondition.setContent(content);
                        sMSCondition.setMobile(mobile);
                        messageSendUtils.sendSms(sMSCondition);
                        logger.info("订单发货" + mobile + ":发送的内容为:" + content);
                    }

                    //发送模板消息
                    String openid = ret.getDataWithException().getOpenid();
                    String page = null;
                    MiniTemplateData data1 = new MiniTemplateData();
                    data1.setKeyName(KEYWORD1);
                    data1.setValue(orderInfo.getOrderNo());
                    MiniTemplateData data2 = new MiniTemplateData();
                    data2.setKeyName(KEYWORD2);
                    data2.setValue(expressInfo.getExpressNo());
                    MiniTemplateData data3 = new MiniTemplateData();
                    data3.setKeyName(KEYWORD3);
                    data3.setValue(expressInfo.getExpressCompany());
                    MiniTemplateData data4 = new MiniTemplateData();
                    data4.setKeyName(KEYWORD4);
                    String orderDate = DateUtil.dateToString(now, "yyyy年MM月dd HH:mm:ss");
                    data4.setValue(orderDate);
                    short msgType2C = MiniMsgTypeEnum.ORDER_DELIVER.getMsgType();
                    MiniMsgCondition miniMsgCondition = OrderUtils.genMiniMsgCondition(openid, page, msgType2C, null, data1, data2, data3, data4);
                    messageServiceClient.sendMiniTemplateMsg(miniMsgCondition);
                } catch (Exception e) {
                    logger.error("订单发货给用户发送消息失败：", e);
                }
                return result;
            }else{
                logger.info("订单：{}  ,用户正在发起售后", orderNo);
                throw new BusinessException(BusinessCode.CODE_405807);
            }
        }finally {
            lock.unlock();
        }
    }
}
